//
//  SourceListViewController.swift
//  clreader
//
//  Created by colin on 2019/3/8.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import MJRefresh

class SourceListViewController: CLBaseViewController {

    private var sourceType = SourceType.精讲
    private lazy var infoTableView = UITableView(frame: CGRect.zero, style: .plain)
    private var infoData = [JSONObject]()
    private var page = Router.defaultPage
    private var taskHandle:URLSessionTask?
    
    convenience init(sourceType:SourceType) {
        self.init()
        self.sourceType = sourceType
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        //topBar
        let topBar = CLNavigationBar().then {
            $0.title = self.sourceType.name
            $0.backHandle = { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
        }
        topBar.show(inView: self.view)
        
        self.view.addSubview(self.infoTableView)
        self.infoTableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(topBar.snp.bottom)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        self.infoTableView.do {
            $0.backgroundColor = UIColor(hex: "f2f3f5")
            $0.separatorStyle = .none
            $0.sectionHeaderHeight = 0
            $0.sectionFooterHeight = 0
            $0.estimatedRowHeight = 0
            $0.register(BookCell.self, forCellReuseIdentifier: BookCell.reuseId)
            $0.dataSource = self
            $0.delegate = self
            $0.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
                self?.refresh()
            })
            $0.mj_header?.beginRefreshing()
        }
    }

}

extension SourceListViewController {
    
    private func refresh() {
        
        self.page = Router.defaultPage
        self.taskHandle?.cancel()
        self.infoTableView.mj_footer = nil
        
        self.taskHandle =
            Router.goods_list(cat_id: nil, type: self.sourceType.intValue,book_type: nil, pageNum: self.page, pageSize: Router.defaultPageSize).request { [weak self] (response:RequestResponse<JSONObject>) in
                
                self?.taskHandle = nil
                self?.infoTableView.mj_header.endRefreshing()
                
                if case .success(let successData,_) = response {
                    if let sources = successData?["rows"] as? [JSONObject] {
                        self?.page += 1
                        self?.infoData = sources
                        if sources.count >= Router.defaultPageSize {
                            self?.infoTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
                                self?.loadMore()
                            })
                        }
                    } else {
                        self?.infoData = []
                    }
                    
                    self?.infoTableView.reloadData()
                }
                
                if case .failure(_,let message) = response {
                    self?.hud.showText(message)
                }
        }
    }
    
    private func loadMore() {
        
        if self.taskHandle != nil {
            return
        }

        self.taskHandle =
            Router.goods_list(cat_id: nil, type: self.sourceType.intValue,book_type: nil, pageNum: self.page, pageSize: Router.defaultPageSize).request { [weak self] (response:RequestResponse<JSONObject>) in
                
                self?.taskHandle = nil
                
                if case .success(let successData,_) = response {
                    if let sources = successData?["rows"] as? [JSONObject] {
                        self?.page += 1
                        self?.infoData += sources
                        if sources.count >= Router.defaultPageSize {
                            self?.infoTableView.mj_footer?.endRefreshing()
                        } else {
                            self?.infoTableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                    } else {
                        self?.infoTableView.mj_footer?.endRefreshingWithNoMoreData()
                        self?.infoData = []
                    }
                    
                    self?.infoTableView.reloadData()
                }
                
                if case .failure(_,let message) = response {
                    self?.infoTableView.mj_footer?.endRefreshing()
                    self?.hud.showText(message)
                }
        }
    }
}

extension SourceListViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.infoData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: BookCell.reuseId) as! BookCell
        cell.refresh(data: self.infoData[indexPath.row])
        return cell
    }
}

extension SourceListViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return BookCell.height
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let goods_id = self.infoData[indexPath.row]["goods_id"] as? Int, goods_id > 0 {
            if self.sourceType == .电子书 {
                let controller = EBookDetailViewController(goods_id: goods_id)
                self.show(controller, sender: nil)
            } else {
                let controller = SourceDetailViewController(sourceType: self.sourceType, goods_id: goods_id)
                controller.hidesBottomBarWhenPushed = true
                self.show(controller, sender: nil)
            }
            
        }
    }
}
